<!-- 用户管理 -->
<template>
  <div class="app-container">
    <el-row :gutter="5">
      <!-- 部门树 -->
      <el-col :lg="4" :xs="24">
        <dept-tree v-model="queryParams.deptId" @node-click="handleQuery" />
      </el-col>

      <!-- 用户列表 -->
      <el-col :lg="20" :xs="24">
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="关键字">
              <el-input
                v-model="queryParams.name"
                placeholder="用户名/账号"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="状态">
              <el-select
                v-model="queryParams.status"
                placeholder="全部"
                clearable
                class="!w-[100px]"
              >
                <el-option label="启用" value="1" />
                <el-option label="禁用" value="0" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery"
                ><i-ep-search />搜索</el-button
              >
              <el-button @click="resetQuery">
                <i-ep-refresh />
                重置</el-button
              >
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never" class="table-container">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button
                  v-hasPerm="['sys:user:add']"
                  type="success"
                  @click="openDialog()"
                  ><i-ep-plus />新增</el-button
                >
                <el-button
                  v-hasPerm="['sys:user:delete']"
                  type="danger"
                  :disabled="removeIds.length === 0"
                  @click="handleDelete()"
                  ><i-ep-delete />删除</el-button
                >
              </div>
            </div>
          </template>

          <el-table
            v-loading="loading"
            :data="pageData"
            class="fix-table"
            fixed
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column
              key="name"
              label="用户名"
              align="center"
              width="120"
              prop="name"
            />
            <el-table-column
              label="账号"
              width="120"
              align="center"
              prop="account"
            />

            <el-table-column label="性别" width="80" align="center" prop="sex">
              <template #default="scope">
                <dictionary
                  v-model="scope.row.sex"
                  type-code="sex"
                  type="tag"
                />
              </template>
            </el-table-column>

            <el-table-column
              label="部门"
              align="center"
              prop="deptNames"
              show-overflow-tooltip
            />

            <el-table-column
              label="角色"
              align="center"
              prop="roleNames"
              show-overflow-tooltip
            />

            <el-table-column
              label="手机号码"
              align="center"
              prop="phone"
              width="120"
            />

            <el-table-column label="状态" align="center" prop="status">
              <template #default="scope">
                <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">{{
                  scope.row.status == 1 ? "启用" : "禁用"
                }}</el-tag>
              </template>
            </el-table-column>

            <el-table-column label="操作" fixed="right" width="220">
              <template #default="scope">
                <el-button
                  v-hasPerm="['sys:user:reset_pwd']"
                  type="primary"
                  size="small"
                  link
                  @click="resetPassword(scope.row)"
                  ><i-ep-refresh-left />重置密码</el-button
                >
                <el-button
                  v-hasPerm="['sys:user:add']"
                  type="primary"
                  link
                  size="small"
                  @click="openDialog(scope.row)"
                  ><i-ep-edit />编辑</el-button
                >
                <el-button
                  v-hasPerm="['sys:user:delete']"
                  type="primary"
                  link
                  size="small"
                  @click="handleDelete(scope.row.id)"
                  ><i-ep-delete />删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-model:total="total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <!-- 用户新增/编辑表单 -->
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="name">
          <el-input
            v-model="formData.name"
            :readonly="!!formData.id"
            placeholder="请输入用户名"
            maxlength="100"
          />
        </el-form-item>

        <el-form-item label="账号" prop="account">
          <el-input
            v-model="formData.account"
            maxlength="50"
            placeholder="请输入用户昵称"
          />
        </el-form-item>

        <el-form-item label="所属部门" prop="deptIds">
          <el-tree-select
            v-model="formData.deptIds"
            placeholder="请选择所属部门"
            :data="deptList"
            :props="props"
            node-key="id"
            filterable
            multiple
            check-strictly
            default-expand-all
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <dictionary v-model="formData.sex" type-code="sex" />
        </el-form-item>

        <el-form-item label="角色" prop="roleIds">
          <el-tree-select
            v-model="formData.roleIds"
            placeholder="选择角色"
            :data="roleList"
            :props="props"
            node-key="id"
            multiple
            filterable
            check-strictly
            default-expand-all
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input
            v-model="formData.phone"
            placeholder="请输入手机号码"
            maxlength="11"
          />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="formData.email"
            placeholder="请输入邮箱"
            maxlength="50"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <dictionary
            v-model="formData.status"
            type-code="status"
            type="radio"
          />
        </el-form-item>
      </el-form>

      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "User",
  inheritAttrs: false,
});

import {
  getUserPage,
  deleteUsers,
  saveUser,
  updateUserPassword,
} from "@/api/user";
import { listDepts } from "@/api/dept";
import { getRoleList } from "@/api/role";

import { DeptVO } from "@/api/dept/types";
import { UserForm, UserQuery, UserPageVO } from "@/api/user/types";
import { RolePageVO } from "@/api/role/types";

const queryFormRef = ref(ElForm); // 查询表单
const userFormRef = ref(ElForm); // 用户表单

const loading = ref(false); //  加载状态
const removeIds = ref([]); // 删除用户ID集合 用于批量删除
const queryParams = reactive<UserQuery>({
  pageNo: 1,
  pageSize: 10,
  deptId: "",
});

const total = ref(0); // 数据总数
const pageData = ref<UserPageVO[]>(); // 用户分页数据
const deptList = ref<TreeResult<DeptVO>[]>(); // 部门下拉数据源
const roleList = ref<TreeResult<RolePageVO>[]>(); // 角色下拉数据源

// 下拉树形选择框
const props = {
  label: "name",
  children: "children",
};

// 弹窗对象
const dialog = reactive({
  visible: false,
  width: 800,
  title: "",
});

// 用户表单数据
const formData = reactive<UserForm>({
  status: "1",
  account: "",
});

// 校验规则
const rules = reactive({
  name: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
  account: [{ required: true, message: "用户账号不能为空", trigger: "blur" }],
  deptIds: [{ required: true, message: "所属部门不能为空", trigger: "blur" }],
  roleIds: [{ required: true, message: "用户角色不能为空", trigger: "blur" }],
  email: [
    {
      pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
  mobile: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getUserPage(queryParams)
    .then(({ data }) => {
      pageData.value = data.content;
      total.value = data.totalElements;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNo = 1;
  queryParams.deptId = undefined;
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 重置密码 */
function resetPassword(row: { [key: string]: any }) {
  ElMessageBox.prompt(
    "请输入用户「" + row.username + "」的新密码",
    "重置密码",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
    }
  ).then(({ value }) => {
    if (!value) {
      ElMessage.warning("请输入新密码");
      return false;
    }
    updateUserPassword(row.id, value).then(() => {
      ElMessage.success("密码重置成功，新密码是：" + value);
    });
  });
}

/** 加载角色下拉数据源 */
async function loadRoleOptions() {
  getRoleList().then((response) => {
    roleList.value = response.data;
  });
}

/** 加载部门下拉数据源 */
async function loadDeptOptions() {
  listDepts().then((res) => {
    deptList.value = res.data;
  });
}

/**
 * 打开弹窗
 *
 * @param type 弹窗类型  用户表单：user-form | 用户导入：user-import
 * @param id 用户ID
 */
async function openDialog(row?: UserPageVO) {
  dialog.visible = true;

  // 用户表单弹窗
  await loadDeptOptions();
  await loadRoleOptions();
  if (row) {
    dialog.title = "修改用户";
    Object.assign(formData, { ...row });
  } else {
    dialog.title = "新增用户";
  }
}

/**
 * 关闭弹窗
 *
 * @param type 弹窗类型  用户表单：user-form | 用户导入：user-import
 */
function closeDialog() {
  dialog.visible = false;

  userFormRef.value.resetFields && userFormRef.value.resetFields();
  userFormRef.value.clearValidate && userFormRef.value.clearValidate();

  formData.id = undefined;
  formData.status = "1";
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  userFormRef.value.validate((valid: any) => {
    if (valid) {
      const userId = formData.id;
      loading.value = true;
      saveUser(formData)
        .then(() => {
          if (userId) {
            ElMessage.success("修改用户成功");
          } else {
            ElMessage.success("新增用户成功");
          }
          closeDialog();
          resetQuery();
        })
        .finally(() => (loading.value = false));
    }
  });
}, 3000);

/** 删除用户 */
function handleDelete(id?: string) {
  const userIds = id ? [id] : removeIds.value;
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteUsers(userIds).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

onMounted(() => {
  handleQuery();
});
</script>

<style lang="scss" scoped>
$varTopPanel: 232px;

.fix-table {
  height: calc(var(--body-height) - $varTopPanel);
}
</style>
